<template>
  <div class="markerOrder">
    <div class="dropdown">
      <el-button type="primary" size="mini" @click.native="subMarker('A')">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane class="market" :label="$t('market.info')" name="first">
        <el-form ref="purchaseRef" :model="prodValue" label-width="100px" :rules="prodValueRules">
          <el-form-item :label="$t('market.billType')" prop="fbillTypeId">
            <el-select
              v-model.trim="prodValue.fbillTypeId"
              size="mini"
              filterable
            >
              <el-option
                v-for="billty in billtypes"
                :key="billty.fid"
                :label="billty.fname"
                :value="billty.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model.trim="prodValue.fbillNo" size="mini" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.fdate')" prop="fdate">
            <el-date-picker
              v-model.trim="prodValue.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              size="mini"
              :placeholder="$t('market.checkDate')"
              style="width: 163px"
            />
          </el-form-item>
          <el-form-item :label="$t('market.cust')" prop="fcustId">
            <el-autocomplete
              ref="custom"
              v-model.trim="prodValue.customer"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              size="mini"
              @focus="queryTBdCustomerList"
              @select="clientData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="clientVisiblit = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.headDelivery')" prop="fheadDeliveryWay">
            <el-autocomplete
              v-model.trim="prodValue.fheadDeliveryWayName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch2"
              size="mini"
              @focus="queryFheadDelivery"
              @select="deliveData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="deliveVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.saler')" prop="fsalerId">
            <el-autocomplete
              v-model.trim="prodValue.fsalerName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch3"
              size="mini"
              @focus="querySalesperson(1)"
              @select="marketData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="marketVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fuserName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.recCondition')" prop="frecConditionId">
            <el-autocomplete
              v-model.trim="prodValue.frecCondition"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch4"
              size="mini"
              @focus="querytReccondition"
              @select="gatheringData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="gatheringVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.paezCom')" prop="fpaezCombo">
            <el-select v-model.trim="prodValue.fpaezCombo" size="mini" filterable>
              <el-option
                v-for="(item, index) in standard"
                :key="index"
                :label="item.fname"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.paezText')" prop="fpaezText">
            <el-input v-model.trim="prodValue.fpaezText" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.paezText1')" prop="fpaezText1">
            <el-input v-model.trim="prodValue.fpaezText1" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.paezText2')" prop="fpaezText2">
            <el-input v-model.trim="prodValue.fpaezText2" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.gold')" prop="fgold">
            <el-input v-model.trim.number="prodValue.fgold" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.note')" prop="fnote" style="width: 33.2%">
            <el-input v-model.trim="prodValue.fnote" size="mini" style="height: 35px" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane class="market" :label="$t('market.fince')" name="second">
        <el-form ref="purchaseRef1" :model="prodValue" label-width="100px" :rules="prodValueRules">
          <el-form-item :label="$t('market.settleCurr')" prop="fsettleCurrId">
            <el-autocomplete
              v-model.trim="prodValue.fsettleCurr"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              size="mini"
              @focus="queryTBdCurrency"
              @select="currencyData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="currencyVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.exchangeType')">
            <el-input v-model.trim="prodValue.fexchangeType" placeholder="请输入汇率类型" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model.trim="prodValue.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')">
            <el-input v-model.trim="prodValue.fexchangeRate" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.priceList')" prop="fpriceListId">
            <el-autocomplete
              v-model.trim="prodValue.fpriceListName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch17"
              size="mini"
              @focus="queryPricerList"
              @select="stickerHandel"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handelPrice"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.overImg')" name="img" class="disRow">
        <div class="positRe">
          <el-upload
            class="avatar-uploader"
            :action="actionURL"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="examine"
          >
            <img
              v-if="prodValue.fapprovalImage"
              :src="prodValue.fapprovalImage"
              class="avatar"
            >
            <div v-if="prodValue.fapprovalImage" class="magnify">
              <i class="el-icon-search" @click.stop="proviewImg(prodValue.fapprovalImage)" />
              <i class="el-icon-delete" @click.stop="prodValue.fapprovalImage=''" />
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"><span>{{ $t('market.upload') }}<!--点击上传--></span></i>
          </el-upload>
        </div>
      </el-tab-pane>
    </el-tabs>
    <tab
      v-show="active === 1"
      ref="tab"
      :forg="forg"
      :msg="prodValue.fpriceListId"
      :msg2="prodValue.fexchangeRate"
      :standardprice="standardPrice"
      :table-data="prodValue.saleDetails"
      @visible="prodOrder"
    />
    <!--客户列表-->
    <client v-if="clientVisiblit" @client="clientData" />
    <!--交货方式列表-->
    <deliver v-if="deliveVisiblit" @delive="deliveData" />
    <!--销售员列表-->
    <market v-if="marketVisiblit" @market="marketData" />
    <!--结算币别列表-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--收款条件列表-->
    <gathering v-if="gatheringVisiblit" @gathering="gatheringData" />
    <!--价目列表-->
    <price v-if="priceVisiblit" :msg2="prodValue.fsettleCurrId" :fcust-id="prodValue.fcustId" @price="stickerHandel" />
    <!--图纸预览-->
    <el-dialog
      v-dialogDrag
      :title="$t('market.preview')"
      model
      :visible.sync="imgVisible"
      append-to-body
      top="10vh"
      width="60%"
    >
      <img :src="priview">
    </el-dialog>
  </div>
</template>
<script>
import {
  queryRate,
  querySalPriceCustomer
} from '@/api/marketManage/marketOrder'
import {
  insertSalFo
} from '@/api/marketManage/forecast'
import jumpMateriel from '@/components/JumpMateriel'
import tab from '@/views/market/marketManage/createMarkerOrder/components/tab'
import mixinsImg from '@/views/market/marketManage/createMarkerOrder/components/mixinsImg'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import mixinShare from '@/views/market/marketManage/createMarkerOrder/components/mixinShare'
import { mapGetters } from 'vuex'
// mixinShare 销售订单、申请单、预测单共同方法
export default {
  name: 'CreateForecast',
  components: {
    tab,
    client: () => import('@/views/market/marketManage/createMarkerOrder/components/client'),
    deliver: () => import('@/views/market/marketManage/createMarkerOrder/components/deliver'),
    market: () => import('@/views/market/marketManage/createMarkerOrder/components/market'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    gathering: () => import('@/views/market/marketManage/createMarkerOrder/components/gathering'),
    price: () => import('@/views/market/marketManage/createMarkerOrder/components/price')
  },
  mixins: [jumpMateriel, mixinsImg, autocomplete, mixinShare],
  data() {
    return {
      active: 1,
      activeName: 'first',
      priview: '', // 预览图片
      imgVisible: false, // 预览图片
      actionURL: '',
      fid: '', // 价目ID
      clientVisiblit: false, // 客户列表弹窗
      priceVisiblit: false, // 价目列表弹窗
      deliveVisiblit: false, // 交货方式弹窗
      marketVisiblit: false, // 销售员弹窗
      currencyVisiblit: false, // 结算币别弹窗
      gatheringVisiblit: false, // 收款条件弹窗
      tableHeight: '50vh', // 弹框中表格高度
      prodValue: { // 表单数据
        fpaezCombo: 18,
        fgold: 0, // 佣金比例
        tableData: '0',
        fdate: new Date(),
        fstart: 0,
        fdocumentStatus: '',
        saler: true,
        fsalType: 0, // 订单类型(正常、特批)
        fapprovalImage: '', // 审批图片
        fbillTypeId: '', // 单据类型
        fcustId: '', // 客户id
        customer: '', // 客户
        fheadDeliveryWayName: '', // 交货方式名称
        fheadDeliveryWay: '', // 交货方式编码
        fnote: '', // 备注
        fsettleCurr: '', // 结算币别名称
        fsettleCurrId: 0, // 结算币别id
        fbillNo: '', // 单据编号
        fsalerId: '', // 销售员ID
        fsaler: '', // 销售员名称
        fpriceListName: '', // 价目表名称
        fpriceListId: 0, // 价目表id
        frecConditionId: '', // 收款条件id
        frecCondition: '', // 收款条件名称
        fisIncludedTax: false, // 是否含税
        fexchangeRate: '', // 汇率
        flocalCurrId: '', // 本位币id
        fexchangeTypeId: '', // 汇率类型id
        fexchangeType: '', // 汇率类型
        flocalCurr: '', // 本位币
        fsysmbol: '', // 币别符号
        saleDetails: []
      },
      fcurrencyId: '', // 汇率类型ID
      frateTypeId: '', // 币别ID
      prodValueRules: { // 提交验证
        fbillTypeId: [
          { required: true, message: '请选择单据类型', trigger: 'change' }
        ], fsalerId: [
          { required: true, message: '请选择销售员', trigger: 'change' }
        ], fsettleCurrId: [
          { required: true, message: '请选择结算币别', trigger: 'change' }
        ], frecConditionId: [
          { required: true, message: '请选择收款条件', trigger: 'change' }
        ], fpaezCombo: [
          { required: true, message: '请选择品质标准', trigger: 'change' }
        ], fpriceListId: [
          { required: false, message: '请选择价目表', trigger: 'blur' }
        ], fdate: [
          { required: true, message: ' 请 选择日期', trigger: 'change' }
        ]
      },
      forg: '',
      standardPrice: {
        fcustId: '',
        fsettleCurr: '',
        fsysmbol: '',
        fexchangeRate: '',
        flocalCurrId: '',
        fsettleCurrId: 0,
        fexchangeTypeId: '',
        fid: ''
      }
    }
  },
  computed: {
    ...mapGetters(['fcurrency'])
  },
  created() {
    const date = new Date().toLocaleDateString().split('/').join('-')
    this.prodValue.fdate = date
    this.queryTBasBilltype('SX_FORRECAST')
    this.queryFpaezCombo()
  },
  methods: {
    // 保存
    subMarker(ev) {
      // 暂存 / 下单(ev: E/A)
      this.prodValue.fdocumentStatus = ev
      this.$refs.purchaseRef.validate(valid => {
        if (!valid) {
          return false
        }
        if (!this.prodValue.fexchangeRate) {
          this.$message.warning('汇率不能为空')
          return false
        }
        if (this.prodValue.saleDetails.length === 0) {
          this.$message.warning('明细信息不能为空')
          return false
        }
        // 删除空行
        this.prodValue.saleDetails.forEach((item, index) => {
          if (!item.fmaterialId) {
            this.prodValue.saleDetails.splice(index, 1)
          }
        })

        for (const item of this.prodValue.saleDetails) {
          if (item.fmaterialId === '' || item.funitId === '' || item.fqty === '' || item.ftaxPrice === '') {
            this.$message.error('表格不能为空或删除空行')
            return false
          }
        }
        for (const item of this.prodValue.planDetails) {
          if (item.frecAdvanceRate === '' || item.frecAdvanCeamount === '') {
            this.$confirm('表格不能为空', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
            return false
          }
        }
        const DATA = this.prodValue
        insertSalFo(DATA).then(res => {
          if (res.code === 0) {
            this.prodValue.fbillNo = res.data.fbillNo
            const fid = res.data.fid
            // 关闭当前页面
            this.$store.dispatch('tagsView/guanbi', this.$route)
            // 跳转到修改页面
            this.$router.push({ path: `/forecastDetail/${fid}` })
            Object.keys(this.prodValue).forEach(res => {
              this.prodValue[res] = ''
              this.prodValue.fsalType = 0
            })
            this.prodValue.saleDetails = []
            this.$message({
              showClose: true,
              type: 'success',
              message: '操作成功'
            })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 获取客户数据(子传父)
    clientData(item) {
      if (item.fcustId) {
        this.prodValue.fcustId = item.fcustId
        this.prodValue.customer = item.fname
        this.standardPrice.fcustId = item.fcustId
        this.clientVisiblit = false
        const DATA = { fcustId: item.fcustId }
        // 获取价目表
        querySalPriceCustomer(DATA).then(res => {
          if (res.code === 0) {
            const item = res.data
            // 成功
            this.prodValue.fpriceListId = item.fpriceListId
            this.standardPrice.fid = item.fpriceListId
            this.prodValue.fpriceListName = item.fpriceListName
            this.prodValue.fsettleCurr = item.fcurrencyName
            this.prodValue.fsettleCurrId = item.fcurrencyId
          } else {
            // 失败-该客户未新增销售价目表为空
            this.prodValue.fpriceListId = 0
            this.prodValue.fpriceListName = ''
            this.$message({ showClose: true, message: res.message, type: 'warning' })
          }
        })
      } else {
        // 没传值，点击关闭按钮
        this.clientVisiblit = false
      }
    },
    // 打开价目表
    handelPrice() {
      if (this.prodValue.fsettleCurrId) {
        this.priceVisiblit = true
      } else {
        this.$message({ showClose: true, message: '请选择结算币别', type: 'warning' })
      }
    },
    // 获取结算币别数据(子传父)
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.prodValue.fsettleCurr = item.fsettleCurrIdName || item.fname
        this.prodValue.fsettleCurrId = item.fsettleCurrId || item.fcurrencyId
        this.prodValue.fsysmbol = item.fsysmbol
        this.currencyVisiblit = item.isCurrencyDialog
        this.standardPrice.fsettleCurrId = item.fsettleCurrId || item.fcurrencyId
        this.standardPrice.fsysmbol = item.fsysmbol
        this.standardPrice.fsettleCurr = item.fsettleCurrIdName || item.fname
        this.prodValue.flocalCurrId && this.querySalerRate()
      }
      this.currencyVisiblit = false
    },
    // 本位币
    currencyData1(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.prodValue.flocalCurr = item.fsettleCurrIdName || item.fname
        this.prodValue.flocalCurrId = item.fsettleCurrId || item.fcurrencyId
        // 获取汇率
        this.prodValue.fsettleCurrId && this.querySalerRate()
      }
    },
    // 查询销售订单汇率
    async querySalerRate() {
      const DATA = {
        fromcurrId: this.prodValue.flocalCurrId,
        tocurrId: this.prodValue.fsettleCurrId,
        queryDate: this.prodValue.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.prodValue.fexchangeRate = RES.exchangeRate
        this.standardPrice.fexchangeRate = RES.exchangeRate
        this.prodValue.fexchangeType = RES.exchangeTypeName
        this.prodValue.fexchangeTypeId = RES.exchangeTypeId
      } else {
        this.prodValue.fexchangeRate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 明细信息、收款计划数据(子传父)
    prodOrder(ev) {
      this.prodValue.saleDetails = ev.saleDetails
      this.prodValue.planDetails = ev.planDetails
    },
    handleTabClick(tab) {
      if (tab.name === 'img') {
        this.active = 0
      } else if (tab.name === 'first' || tab.name === 'second') {
        this.active = 1
        this.prodValue.flocalCurrId = this.fcurrency.fcurrencyId
        this.prodValue.flocalCurr = this.fcurrency.fcurrencyName
      }
    },
    // 预览图片
    proviewImg(img) {
      this.imgVisible = true
      this.priview = img
    }
  }
}
</script>
<style lang="scss">
.el-form-item__error {
  top: 11px;
  left: 15px;
}
</style>
<style scoped lang="scss">
.markerOrder {
  @include listBom;
  .el-form-item__label {
    font-size: 12px;
  }
  .el-tabs {
    &::v-deep .el-tabs__content {
      .market {
        height: 12.5vh;
      }
      overflow-y: auto;
    }
    &::v-deep .el-tabs__item {
      height: 30px;
      line-height: 30px;
    }
    &::v-deep .el-tabs__content {
      padding: 5px 17px;
    }
    .el-tabs ::v-deep .el-tabs__header{
      margin: 0 0 5px;
    }
    .disRow {
      height: calc(100vh - 270px);

      .positRe {
        position: relative;
        margin-left: 100px;
        margin-top: 20px;

        .avatar-uploader .el-upload {
          height: 27.6vh;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
          border-color: #409EFF;
        }

        .avatar-uploader-icon {
          font-size: 18px;
          color: #8c939d;
          width: 11.96vw;
          height: 27.6vh;
          line-height: 27.6vh;
          text-align: center;
          border: 1px solid #aaa;
          border-radius: 6px;
          background: #eee;

          span {
            color: #409eff;
          }
        }

        .avatar {
          width: 11.96vw;
          height: 27.6vh;
          display: block;
          border-radius: 6px;
        }

        .avatar-uploader {
          width: 11.96vw;
          height: 100%;
          transition: all 1s;
        }

        .avatar-uploader:hover .magnify {
          display: block;
        }

        .magnify {
          display: none;
          height: 27.6vh;
          width: 11.96vw;
          background-color: rgba(0, 0, 0, .4);
          position: absolute;
          top: 0;
          line-height: 27.6vh;
          border-radius: 6px;

          i {
            font-size: 24px;
            color: #fff;
            padding: 0 15px;
          }
        }
      }
    }
    .el-input::v-deep .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .el-form {
      display: flex;
      flex-wrap: wrap;

      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        margin-bottom: 5px;
        //&::v-deep .el-input--mini .el-input__inner{
        //  height: 22px;
        //}
        .btnType {
          margin-right: 20px;
        }

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
}

.el-input__icon {
  cursor: pointer;
}
</style>
